package org.ediba.siri.web;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;

import org.apache.commons.beanutils.BeanMap;
import org.ediba.siri.core.image.domain.Image;
import org.ediba.siri.core.image.service.ImageService;
import org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView;

public class ImagesJasperReportsPdfView extends JasperReportsPdfView {
		
	private ImageService imageService;
	public void setImageService(ImageService imageService){this.imageService = imageService;}

	@Override
	protected JRDataSource convertReportData(Object value) throws IllegalArgumentException {
		
		@SuppressWarnings("unchecked")
		Collection<Image> _images = (Collection<Image>) value;
		Collection<Map<String,Object>> _renderableImages = new ArrayList<Map<String,Object>>(_images.size());
		BeanMap _imageBeanMap;
		Map<String,Object> _imageDynMap;
		Map<String,InputStream> _thumb;
		InputStream _inputStream = null;
		
		for (Image _image : _images) {
			_thumb = this.imageService.retrieveThumb(_image.getId());
			if (_thumb != null)
				for (Map.Entry<String,InputStream> _thumbEntry : _thumb.entrySet())
					_inputStream = _thumbEntry.getValue();
			else 
				try {_inputStream = new FileInputStream(this.getServletContext().getRealPath("/images/broken-image.png"));}
				catch (FileNotFoundException e) {e.printStackTrace();}
				
			_imageBeanMap = new BeanMap(_image);
			_imageDynMap = new HashMap<String, Object>(_imageBeanMap.size() + 1); 
			_imageDynMap.put("data", _inputStream);
			for (Object key : _imageBeanMap.keySet())
				_imageDynMap.put((String)key, _imageBeanMap.get((String)key));
				
			_renderableImages.add(_imageDynMap);
		}
		
		return super.convertReportData(new JRMapCollectionDataSource(_renderableImages));
	}

}
